<?php
namespace Modules\Buy\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\Buy\Entities\Arr;
use Modules\Buy\Entities\Brand;
use Modules\Buy\Entities\Brandcate;
use Modules\Buy\Entities\Catearr;
use Modules\Buy\Entities\Catego;
use Modules\Buy\Entities\Good;
use Modules\Buy\Http\Requests\GoodRequest;
class GoodController extends Controller
{
    //显示列表
    public function index()
    {
        $data = Good::paginate(10);
        return view('buy::good.index', compact('data'));
    }

    //创建视图
    public function create(Good $good)
    {
//        dd(123);
//        获取所有的品牌，供商品选择
        $brand = Brand::get();
//        dd($brand->toArray());
        return view('buy::good.create',compact('good','brand'));
    }

    //保存数据
    public function store(GoodRequest $request,Good $good)
    {
//        dd($request->all());
        $post = $request->all();
        $post['can_id'] = implode(',',$post['can_id']);
        $good->fill($post);
        $good->save();
        return redirect('/buy/good')->with('success', '保存成功');
    }

    //显示记录
    public function show(Good $field)
    {
        return view('buy::good.show', compact('field'));
    }

    //编辑视图
    public function edit(Good $good)
    {
//        dd($good->toArray());
        $brand = Brand::get();
//        难点来了:判断默认分类，属性选中
        $categorys = Catego::where('pid',0)->get();

//获取当前编辑商品所属品牌的可用分类
        $brandCate = Brandcate::where('brand_id',$good['brand_id'])->pluck('cate_id');
//找到对应品牌的可用分类数据
        $cate = Catego::whereIn('id',$brandCate)->get();
 //获取当前商品的所属分类的可用属性
        $attrids = Catearr::where('cid',$good['cate_id'])->pluck('aid');
        $attrs = Arr::whereIn('id',$attrids)->get();
        return view('buy::good.edit', compact('good','brand','cate','attrs','categorys'));// return view('buy::good.edit', compact('good','brand'));
    }

    //更新数据
    public function update(GoodRequest $request, Good $good)
    {
//        $good->update($request->all());
        $post = $request->all();
        $post['can_id'] = implode(',',$post['can_id']);
        $good->update($post);
        return redirect('/buy/good')->with('success','更新成功');
    }

    //删除模型
    public function destroy(Good $good)
    {
        $good->delete();
        return redirect('buy/good')->with('success','删除成功');
    }

//    Ajax异步请求
//    为所有的品牌异步获取分类添加获取方法
    public function getbrandcate($id)
    {
//        return 123;
//        在这里获取所有的顶级分类数据，然后返回出去，已知的是品牌的id
//        通过中间表找
        $cate = Brandcate::where('brand_id',$id)->pluck('cate_id');
//        在根据找到的分类id找对应的分类数据
        $catenum = Catego::whereIn('id',$cate)->get();
        return $catenum;
    }

//    获取三级分类下面的可用属性
    public function getattr($id)
    {
        $attrids = Catearr::where('cid',$id)->pluck('aid');
        $attrs = Arr::whereIn('id',$attrids)->get();
        return $attrs;
    }
}
